package com.example.prjbackend.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.prjbackend.entity.User;
import com.example.prjbackend.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// 用户服务类
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册方法
     * @param user 用户对象
     * @return 注册是否成功
     */
    public boolean register(User user) {
        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        Long count = userMapper.selectCount(queryWrapper);

        if (count > 0) {
            return false; // 用户名已存在
        }

        // 插入新用户
        int result = userMapper.insert(user);
        return result > 0;
    }

    /**
     * 用户登录方法
     * @param username 用户名
     * @param password 密码
     * @return 登录成功返回用户对象，失败返回null
     */
    public User login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username)
                .eq("password", password);

        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return 用户对象
     */
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

}

